import { motion, AnimatePresence } from "motion/react";
import { useState, useEffect } from "react";
import {
  Copy,
  Edit3,
  RefreshCw,
  Check,
  CheckCheck,
  Heart,
  Share2,
  Download,
  MoreHorizontal
} from "lucide-react";
import { Button } from "./ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip";

interface Message {
  id: string;
  text: string;
  sender: "user" | "assistant";
  timestamp: Date;
  status?: "sending" | "sent" | "delivered" | "error";
  reactions?: string[];
  isStreaming?: boolean;
}

interface MessageBubbleProps {
  message: Message;
  isEditing: boolean;
  editedText: string;
  onCopyMessage: (text: string, messageId: string) => void;
  onEditMessage: (messageId: string) => void;
  onSaveEditedMessage: (messageId: string) => void;
  onCancelEdit: () => void;
  onAddReaction: (messageId: string, reaction: string) => void;
  onEditChange: (text: string) => void;
  onRegenerateMessage: (messageId: string) => void;
  copiedMessageId?: string | null;
}

export function MessageBubble({
  message,
  isEditing,
  editedText,
  onCopyMessage,
  onEditMessage,
  onSaveEditedMessage,
  onCancelEdit,
  onAddReaction,
  onEditChange,
  onRegenerateMessage,
  copiedMessageId,
}: MessageBubbleProps) {
  const [showActions, setShowActions] = useState(false);
  const [showReactionMenu, setShowReactionMenu] = useState(false);
  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  const isUser = message.sender === "user";
  const isCopied = copiedMessageId === message.id;

  // 常用表情
  const quickReactions = ["👍", "❤️", "😊", "🎉", "🔥", "💡"];

  // 检测是否为移动端
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 格式化时间
  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 处理复制
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(message.text);
      onCopyMessage(message.text, message.id);
      if (isMobile) setShowMobileMenu(false);
    } catch (error) {
      console.error('Failed to copy:', error);
    }
  };

  // 处理重新生成
  const handleRegenerate = () => {
    onRegenerateMessage(message.id);
    setShowActions(false);
    if (isMobile) setShowMobileMenu(false);
  };

  // 处理编辑
  const handleEdit = () => {
    onEditMessage(message.id);
    if (isMobile) setShowMobileMenu(false);
  };

  // 处理添加反应
  const handleAddReaction = (reaction: string) => {
    onAddReaction(message.id, reaction);
    setShowReactionMenu(false);
    if (isMobile) setShowMobileMenu(false);
  };

  return (
    <motion.div
      whileHover={{ scale: 1.01 }}
      whileTap={{ scale: 0.99 }}
      className={`relative group ${
        isUser
          ? "ml-auto"
          : "mr-auto"
      }`}
      onMouseEnter={() => !isMobile && setShowActions(true)}
      onMouseLeave={() => {
        !isMobile && setShowActions(false);
        !isMobile && setShowReactionMenu(false);
      }}
      onClick={(e) => {
        // 防止点击事件冒泡
        if (isMobile) {
          e.stopPropagation();
        }
      }}
    >
      {/* 消息气泡 */}
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        className={`
          relative rounded-2xl px-3 py-2 md:px-4 md:py-3 max-w-full md:max-w-[600px]
          ${isUser
            ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg'
            : 'bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 shadow-md border border-slate-200 dark:border-slate-700'
          }
          ${message.isStreaming ? 'animate-pulse' : ''}
        `}
      >
        {/* 编辑模式 */}
        {isEditing ? (
          <div className="space-y-2 md:space-y-3">
            <textarea
              value={editedText}
              onChange={(e) => onEditChange(e.target.value)}
              className="w-full bg-white/20 dark:bg-slate-700/20 border border-white/30 dark:border-slate-600/30 rounded-xl p-2 md:p-3 text-white dark:text-slate-100 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 backdrop-blur-sm"
              rows={3}
              autoFocus
              placeholder="编辑消息..."
            />
            <div className="flex space-x-2">
              <Button
                onClick={() => onSaveEditedMessage(message.id)}
                className="bg-blue-500 hover:bg-blue-600 text-white text-xs md:text-sm h-8 md:h-9"
              >
                保存
              </Button>
              <Button
                variant="outline"
                onClick={onCancelEdit}
                className="border-white/30 text-white hover:bg-white/20 text-xs md:text-sm h-8 md:h-9"
              >
                取消
              </Button>
            </div>
          </div>
        ) : (
          <>
            {/* 消息内容 */}
            <div className="text-sm leading-relaxed whitespace-pre-wrap break-words">
              {message.text}
              {message.isStreaming && (
                <motion.span
                  animate={{ opacity: [0, 1, 0] }}
                  transition={{ duration: 1, repeat: Infinity }}
                  className="inline-block w-1.5 h-3 md:w-2 md:h-4 bg-current ml-1 rounded"
                />
              )}
            </div>

            {/* 反应表情 */}
            {message.reactions && message.reactions.length > 0 && (
              <div className="flex flex-wrap gap-1 mt-2">
                <AnimatePresence>
                  {message.reactions.map((reaction, index) => (
                    <motion.span
                      key={index}
                      initial={{ scale: 0, rotate: -180 }}
                      animate={{ scale: 1, rotate: 0 }}
                      className="text-xs md:text-sm bg-white/20 dark:bg-slate-700/20 rounded-full px-1.5 py-0.5 md:px-2 md:py-1 backdrop-blur-sm"
                    >
                      {reaction}
                    </motion.span>
                  ))}
                </AnimatePresence>
              </div>
            )}

            {/* 底部信息栏 */}
            <div className={`flex items-center justify-between mt-2 pt-2 border-t ${
              isUser
                ? 'border-white/20'
                : 'border-slate-200 dark:border-slate-700'
            }`}>
              {/* 时间戳 */}
              <span className={`text-xs ${
                isUser
                  ? 'text-white/70'
                  : 'text-slate-500 dark:text-slate-400'
              }`}>
                {formatTime(message.timestamp)}
              </span>

              {/* 状态指示器 */}
              {message.status && (
                <div className="flex items-center">
                  {message.status === "sending" && (
                    <div className="w-1.5 h-1.5 md:w-2 md:h-2 bg-yellow-400 rounded-full animate-pulse" />
                  )}
                  {message.status === "sent" && (
                    <Check className="w-2.5 h-2.5 md:w-3 md:h-3 text-white/50" />
                  )}
                  {message.status === "delivered" && (
                    <CheckCheck className="w-2.5 h-2.5 md:w-3 md:h-3 text-white/50" />
                  )}
                  {message.status === "error" && (
                    <div className="w-1.5 h-1.5 md:w-2 md:h-2 bg-red-400 rounded-full" />
                  )}
                </div>
              )}
            </div>
          </>
        )}
      </motion.div>

      {/* 移动端菜单按钮 */}
      {isMobile && !isEditing && (
        <div className={`
          absolute -top-10 flex
          ${isUser ? 'right-0' : 'left-0'}
        `}>
          <Button
            variant="outline"
            onClick={(e) => {
              e.stopPropagation();
              setShowMobileMenu(!showMobileMenu);
            }}
            className="h-8 w-8 p-0 bg-white dark:bg-slate-800 shadow-md border border-slate-200 dark:border-slate-700"
          >
            <MoreHorizontal className="w-4 h-4 text-slate-600 dark:text-slate-300" />
          </Button>
        </div>
      )}

      {/* 移动端菜单 */}
      {isMobile && showMobileMenu && !isEditing && (
        <div 
          className={`
            absolute top-full mt-2 rounded-xl shadow-xl border p-2 z-30 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700
            ${isUser ? 'right-0' : 'left-0'}
          `}
          onClick={(e) => e.stopPropagation()}
        >
          <div className="grid grid-cols-3 gap-1">
            <Button
              variant="outline"
              onClick={handleCopy}
              className="h-10 w-10 p-0 text-xs hover:bg-slate-100 dark:hover:bg-slate-700"
            >
              <div className="flex flex-col items-center">
                {isCopied ? (
                  <Check className="w-4 h-4 text-green-500" />
                ) : (
                  <Copy className="w-4 h-4" />
                )}
                <span className="text-xs mt-1">{isCopied ? '已复制' : '复制'}</span>
              </div>
            </Button>

            {isUser && (
              <Button
                variant="outline"
                onClick={handleEdit}
                className="h-10 w-10 p-0 text-xs hover:bg-slate-100 dark:hover:bg-slate-700"
              >
                <div className="flex flex-col items-center">
                  <Edit3 className="w-4 h-4" />
                  <span className="text-xs mt-1">编辑</span>
                </div>
              </Button>
            )}

            {!isUser && (
              <Button
                variant="outline"
                onClick={handleRegenerate}
                className="h-10 w-10 p-0 text-xs hover:bg-slate-100 dark:hover:bg-slate-700"
              >
                <div className="flex flex-col items-center">
                  <RefreshCw className="w-4 h-4" />
                  <span className="text-xs mt-1">重新生成</span>
                </div>
              </Button>
            )}

            <Button
              variant="outline"
              onClick={() => {
                setShowReactionMenu(!showReactionMenu);
                setShowMobileMenu(false);
              }}
              className="h-10 w-10 p-0 text-xs hover:bg-slate-100 dark:hover:bg-slate-700"
            >
              <div className="flex flex-col items-center">
                <Heart className="w-4 h-4" />
                <span className="text-xs mt-1">表情</span>
              </div>
            </Button>

            <Button
              variant="outline"
              className="h-10 w-10 p-0 text-xs hover:bg-slate-100 dark:hover:bg-slate-700"
            >
              <div className="flex flex-col items-center">
                <Share2 className="w-4 h-4" />
                <span className="text-xs mt-1">分享</span>
              </div>
            </Button>

            <Button
              variant="outline"
              className="h-10 w-10 p-0 text-xs hover:bg-slate-100 dark:hover:bg-slate-700"
            >
              <div className="flex flex-col items-center">
                <Download className="w-4 h-4" />
                <span className="text-xs mt-1">下载</span>
              </div>
            </Button>
          </div>
        </div>
      )}

      {/* 快捷操作菜单 - 桌面端 */}
      {!isMobile && (
        <>
          <AnimatePresence>
            {showActions && !isEditing && (
              <motion.div
                initial={{ opacity: 0, scale: 0.8, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.8, y: 10 }}
                className={`
                  absolute top-full mt-2 rounded-xl shadow-xl border p-1 z-20
                  ${isUser
                    ? 'right-0 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700'
                    : 'left-0 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700'
                  }
                `}
              >
                <div className="flex flex-col">
                  {/* 复制 */}
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="outline"
                          onClick={handleCopy}
                          className="justify-start h-8 px-3"
                        >
                          {isCopied ? (
                            <Check className="w-4 h-4 text-green-500" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                          <span className="ml-2">{isCopied ? '已复制' : '复制'}</span>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>复制消息内容</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>

                  {/* 编辑（仅用户消息） */}
                  {isUser && (
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="outline"
                            onClick={handleEdit}
                            className="justify-start h-8 px-3"
                          >
                            <Edit3 className="w-4 h-4" />
                            <span className="ml-2">编辑</span>
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>编辑消息</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  )}

                  {/* 重新生成（仅AI消息） */}
                  {!isUser && (
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="outline"
                            onClick={handleRegenerate}
                            className="justify-start h-8 px-3"
                          >
                            <RefreshCw className="w-4 h-4" />
                            <span className="ml-2">重新生成</span>
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>重新生成回复</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  )}

                  {/* 分享 */}
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="outline"
                          className="justify-start h-8 px-3"
                        >
                          <Share2 className="w-4 h-4" />
                          <span className="ml-2">分享</span>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>分享消息</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>

                  {/* 下载 */}
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="outline"
                          className="justify-start h-8 px-3"
                        >
                          <Download className="w-4 h-4" />
                          <span className="ml-2">下载</span>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>下载为文件</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 快速反应菜单 - 桌面端 */}
          <AnimatePresence>
            {showReactionMenu && !isEditing && (
              <motion.div
                initial={{ opacity: 0, scale: 0.8, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.8, y: 10 }}
                className={`
                  absolute top-full mt-2 rounded-xl shadow-xl border p-2 z-20
                  ${isUser
                    ? 'right-0 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700'
                    : 'left-0 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700'
                  }
                `}
              >
                <div className="grid grid-cols-3 gap-1">
                  {quickReactions.map((reaction) => (
                    <Button
                      key={reaction}
                      variant="outline"
                      onClick={() => handleAddReaction(reaction)}
                      className="h-8 w-8 p-0 text-lg hover:bg-slate-100 dark:hover:bg-slate-700"
                    >
                      {reaction}
                    </Button>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 悬浮操作按钮 - 桌面端 */}
          {showActions && !isEditing && (
            <div className={`
              absolute -top-12 flex space-x-1
              ${isUser ? 'right-0' : 'left-0'}
            `}>
              {/* 表情按钮 */}
              <Button
                variant="outline"
                onClick={() => setShowReactionMenu(!showReactionMenu)}
                className="h-8 w-8 p-0 bg-white dark:bg-slate-800 shadow-md border border-slate-200 dark:border-slate-700"
              >
                <Heart className="w-4 h-4 text-slate-600 dark:text-slate-300" />
              </Button>
            </div>
          )}
        </>
      )}

      {/* 快速反应菜单 - 移动端 */}
      {isMobile && showReactionMenu && !isEditing && (
        <div 
          className={`
            absolute top-full mt-2 rounded-xl shadow-xl border p-2 z-30 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700
            ${isUser ? 'right-0' : 'left-0'}
          `}
          onClick={(e) => e.stopPropagation()}
        >
          <div className="grid grid-cols-6 gap-1">
            {quickReactions.map((reaction) => (
              <Button
                key={reaction}
                variant="outline"
                onClick={() => handleAddReaction(reaction)}
                className="h-10 w-10 p-0 text-lg hover:bg-slate-100 dark:hover:bg-slate-700"
              >
                {reaction}
              </Button>
            ))}
          </div>
        </div>
      )}
    </motion.div>
  );
}
